/*
 * MinIO Cloud Storage (C) 2018 MinIO, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React from "react";
import { connect } from "react-redux"
import { createStyles, makeStyles, withStyles, Theme } from '@material-ui/core/styles';
import ReactEcharts from 'echarts-for-react';
import * as echarts from 'echarts';
import Alert from '@material-ui/lab/Alert';
import IconButton from '@material-ui/core/IconButton';
import Collapse from '@material-ui/core/Collapse';
import CloseIcon from '@material-ui/icons/Close';
import api from "../../../common/api";
import { ChartUrl, beforeNowtimeByMinu, timeConvert } from "./types";

const styles = (theme: Theme) =>
  createStyles({
    alert: {
      position: "absolute",
      width: "100%",
      textAlign: "center",
      zIndex: 1000, 
      top: 35
    },
    alertPop: {
      margin: "0 auto",
      width: "130px"
    },
    chart: {
      height: '350px', 
      width: '100%', 
      marginTop: -20,
      marginBottom: -40
    },
});
interface ChartState {
  classes: any;
  // inputNode: string
}
export class NodeReadWrite extends React.Component<ChartState, any> {
  constructor(props:any){
    super(props);
    this.state = {
      records: [],
      xrecord:[],
      recordsData:[],
      loading: false,
      oldNode:"",
      msg:"",
      dataWarn:"",
      open: false
    };
  };
  setOpen(a:boolean){
    this.setState({
      open: a
    })
  }
  getChart() {
    // 统计磁盘 1分钟每秒 读写 I/O ，Mb/S3
    let url = ChartUrl+"(rate(node_disk_read_bytes_total%7Bdevice%3D%27sda%27%7D%5B1m%5D)%2Brate(node_disk_written_bytes_total%7Bdevice%3D%27sda%27%7D%5B1m%5D))%2F1024%2F1024&start="+Date.parse(beforeNowtimeByMinu(60)).toString().substring(0,10)+"&end="+Date.parse(beforeNowtimeByMinu(0)).toString().substring(0,10)+"&step=14";
    api
      .invoke("GET", url)
      .then((res) => {
        var xrec = new Array();
        var rootData = res.data.result;
        if(rootData != []){
          for(var i=0;i<rootData.length;i++){
            for(var a=0;a<rootData[i].values.length;a++){
              rootData[i].values[a][0] = timeConvert(parseInt(rootData[i].values[a][0]));
              rootData[i].values[a][1] = parseFloat(rootData[i].values[a][1])
              rootData[0].values[a][1] += rootData[i].values[a][1]
            }
          }
          for(var n=0;n<rootData[0].values.length;n++){
            xrec[n]=rootData[0].values[n][0]
          }
          var length = rootData.length
          // rootData[0].values.map(function (item:any) {
          //   return [item[0], item[1]/length]
          // })
          let recData =  {
            type: 'line',
            itemStyle: {
              color: '#5793f3'
            },
            areaStyle: {
              // @ts-ignore
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    offset: 0,
                    color: 'rgba(170,200,249,0.6)'
                }, {
                    offset: 1,
                    color: 'rgba(87,147,243,0.8)'
                }])
            },
            data: rootData[0].values.map(function (item:any) {
              return [item[0], (item[1]/length).toFixed(2)]
            })
          }
          // console.log(xrec)
          // console.log(rootData[i].values)
          this.setState({
            xrecord: xrec,
            recordsData: recData,
          });
          
        }else{
          this.setState({
            dataWarn: "暂无数据",
            xrecord: ""
          })
          this.setOpen(true);
        }
      })
      .catch(err => {
        this.setState({
          dataWarn: "暂无数据",
          xrecord: ""
        })
        this.setOpen(true);
      });
  }
  componentDidMount(): void {
    var that = this
    that.getChart();
    var timer = setInterval(() => {
      let url = window.location.href
      if(url.indexOf("/dashboard") != -1){
        that.getChart();
      }else{
        clearInterval(timer)
      }
    }, 30000)
  }
  getOption= () => ({
      title: {
        text: this.state.msg
      },
      tooltip: {
        trigger: 'axis',
      },
      grid: {
          left: 35,
          right: 10
      },
      xAxis: {
          data: this.state.xrecord
      },
      yAxis: {
        name: 'Mb/S',
        splitLine: {
          show: true
        }
      },
      series: this.state.recordsData
  });
  render() {
    const { classes } = this.props;
    return (
      <div style={{position: "relative"}}>
        {this.state.open ? (
        <div className={classes.alert}>
          <Collapse in={this.state.open} className={classes.alertPop}>
            <Alert severity="error" style={{padding: "0 16px"}}>
              {this.state.dataWarn}
            </Alert>
          </Collapse>
        </div>
        ):(
          <ReactEcharts
          ref="chart"
          option={this.getOption()}
          className={classes.chart}/>
          )}
      </div>
    );
  }
};
export default withStyles(styles)(NodeReadWrite)